package com.dingding.special.common.aop;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import com.dingding.common.core.base.controller.BaseController;
import com.dingding.special.common.exception.bussiness.BussinessException;
import com.dingding.special.common.exception.server.ServerException;

@Aspect
public class ControllerExceptionHandler extends BaseController {

	private Logger log = Logger.getLogger(this.getClass());

	@Around("execution(* com.dingding.special.controller.*.*(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)) && args(request,response)")
	public void aroundMethod(ProceedingJoinPoint jp, HttpServletRequest request, HttpServletResponse response) {

		// 获取被调用的方法名称
		MethodSignature signature = (MethodSignature) jp.getSignature();
		Method method = signature.getMethod();

		try {
			jp.proceed();
		} catch (BussinessException e) {
			log.error("拦截到异常业务异常BussinessException,错误码为:" + e.getCode() + ",错误信息为:" + e.getMessage());
			super.generateErrorResponse(response, e.getCode(), e.getMessage());
		} catch (ServerException e) {
			log.error("拦截到异常服务器ServerException,错误码为:" + e.getCode() + ",错误信息为:" + e.getMessage());
			super.generateErrorResponse(response, e.getCode(), e.getMessage());
		} catch (Throwable e) {
			log.error("拦截到非业务异常！方法为：" + method.getName(), e);
			super.generateErrorResponse(response, HttpStatus.SC_INTERNAL_SERVER_ERROR, "服务器异常");
		}
	}
	
}
